/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.bizentity.json.increment;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.inspur.edp.bef.bizentity.common.BizEntityJsonConst;
import com.inspur.edp.bef.bizentity.increment.entity.determination.AddedDtmIncrement;
import com.inspur.edp.bef.bizentity.increment.entity.determination.DtmIncrement;
import com.inspur.edp.bef.bizentity.json.operation.BizDeterminationSerializer;
import com.inspur.edp.bef.bizentity.operation.Determination;
import com.inspur.edp.cef.designtime.api.json.CefNames;
import com.inspur.edp.cef.designtime.api.json.SerializerUtils;
import java.io.IOException;

public class DtmIncrementSerializer extends JsonSerializer<DtmIncrement> {

  @Override
  public void serialize(DtmIncrement value, JsonGenerator gen,
      SerializerProvider serializerProvider) throws IOException {
    SerializerUtils.writeStartObject(gen);
    writeBaseInfo(value, gen);
    SerializerUtils.writeEndObject(gen);
  }

  private void writeBaseInfo(DtmIncrement value, JsonGenerator gen) {
    SerializerUtils
        .writePropertyValue(gen, CefNames.IncrementType, value.getIncrementType().toString());
    switch (value.getIncrementType()) {
      case Added:
        writeAddedIncrement((AddedDtmIncrement) value, gen);
        break;
      case Modify:
//                writeModifyIncrement((ModifyMgrActionIncrement) value, gen);
        break;
      case Deleted:
//                writeDeletedIncrement((DeletedEntityIncrement) value, gen);
        break;
      default:
        throw new RuntimeException("增量序列化失败，不存在增量类型" + value.getIncrementType().toString());
    }
  }

  private void writeAddedIncrement(AddedDtmIncrement increment, JsonGenerator gen) {
    SerializerUtils.writePropertyName(gen, BizEntityJsonConst.AddedAction);
    writeBaseActionInfo(increment.getAction(), gen);
  }

  private void writeBaseActionInfo(Determination action, JsonGenerator gen) {
    BizDeterminationSerializer convertor = new BizDeterminationSerializer();
    try {
      convertor.serialize(action, gen, null);
    } catch (Exception e) {
      throw new RuntimeException("联动计算" + action.getCode() + "序列化失败：", e);
    }
  }
}
